/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { randomBytes } from 'crypto';
import { AddressInfo } from 'net';
import process from 'process';

import { getCurrentProjectCacheDirHash } from '../../../cli/wrapper/util.js';
import { CUR_HVIGOR_VERSION } from '../../../cli/wrapper/wrapper-const.js';
import { HVIGOR_ENGINE_PACKAGE_NAME } from '../../../common/const/const.js';
import { hash } from '@ohos/hvigor-common';
import { HvigorDaemonLogger } from '../log/hvigor-daemon-log.js';
import { SessionIdHelper } from '../session/session-id.js';

import { DaemonInfo, DaemonState } from './daemon-info.js';

const _log = HvigorDaemonLogger.getLogger('daemon');

class DaemonInfoService {
  createDefaultDaemonInfo(serverAddress: AddressInfo, sessionId: string): DaemonInfo {
    _log.debug(`hvigor daemon: Create default daemon info. execArgv=${[...process.execArgv]}`);
    const cacheDirHash = getCurrentProjectCacheDirHash();
    _log.debug(`hvigor work dir: ${cacheDirHash}`);
    const currentPkgPath = require.resolve(HVIGOR_ENGINE_PACKAGE_NAME);
    return {
      pid: process.pid,
      state: DaemonState.IDLE,
      address: serverAddress.address,
      cwdPath: process.cwd(),
      hvigorVersion: CUR_HVIGOR_VERSION,
      keyId: randomBytes(20).toString('hex'),
      nodeParams: hash(`${currentPkgPath}${cacheDirHash}${process.execArgv.toString()}`),
      nodeVersion: process.version,
      port: serverAddress.port,
      lastUsedTime: Date.now(),
      createdBy: process.env['CREATED_BY'] ?? 'command',
      sessionId: SessionIdHelper.encryptPwdByDefaultMaterial(sessionId, _log),
    };
  }
}

export const defaultDaemonInfoService = new DaemonInfoService();
